package Thread;
class MyBlockingQueue {
    private String[] data=null;

    //队首
    private int head=0;
    //队尾
    private int tail=0;
    //元素个数
    private int count=0;
    public MyBlockingQueue() {
        data=new String[10];
    }
    public synchronized void put(int n) throws InterruptedException {
        while(count>=data.length){
            wait();
        }
        data[tail++]=String.valueOf(n);
        count++;
        if(tail>=data.length){
            tail=0;
        }
        notify();
    }
    public synchronized String take() throws InterruptedException {
        while(count<=0){
            wait();
        }
        String ret = data[head];
        head++;
        if (head >= data.length) {
            head = 0;
        }
        count--;
        notify();
        return ret;
    }
}
public class Demo31 {
    public static void main(String[] args) {
    MyBlockingQueue myBlockingQueue=new MyBlockingQueue();

    Thread producer= new Thread(()->{
        int n=0;
        while(true){
            try {
                myBlockingQueue.put(n );
                System.out.println("生产元素 " + n);
                n++;
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    },"producer");
    Thread consumer= new Thread(()->{
        while(true){
            String n=null;
            try {
                n = myBlockingQueue.take();
                System.out.println("消费元素 " + n);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    },"consumer");
    producer.start();
    consumer.start();
    }
}
